#!/usr/bin/env python
# --*-- coding: utf-8 --*--

# index.py

from pyjamas.ui import HTML, RootPanel, HorizontalPanel, VerticalPanel, DockPanel, HTMLPanel, TabPanel, Grid
from pyjamas.ui import SimplePanel, Button, ListBox, Label, HasAlignment, TextBox, Frame
from pyjamas.ui import MenuBar, MenuItem
from pyjamas.ui import DialogBox
from pyjamas.CountryListBox import CountryListBox
from pyjamas.Tooltip import Tooltip, TooltipListener
from pyjamas.AutoComplete import AutoCompleteTextBox
from pyjamas.HTTPRequest import HTTPRequest
from pyjamas.JSONParser import JSONParser
from pyjamas import DOM, Window
from Widgets import SolarCanvas, Calendar, RoundPanel, NumericTextBox
from dbwidgets import CrudPanel, FormEditRecord

def makerecord(colName, colRepr = None, colValue = '', isId = False, isVisible = True):
    record = {}
    record['colName'] = colName
    if not colRepr:
        colRepr = colName
    record['colRepr'] = colRepr
    record['colValue'] = colValue
    record['isId'] = isId
    record['isVisible'] = isVisible
    return record

#class Record:
#    def __init__(self, colName, colRepr = None, colValue = '', isId = False, isVisible = True):
#        self.colName = colName
#        if not colRepr:
#            colRepr = self.colName
#        self.colRepr = colRepr
#        self.colValue = colValue
#        self.isVisible = isVisible
#        self.isId = isId
#    def get(self, prop):
#        try:
#            return getattr(self, prop)
#        except:
#            return ''
        
class AjaxLoader:
    def __init__(self, lblAjax = None):
        self.lblAjax = lblAjax
        if self.lblAjax:
            self.lblAjax.setVisible(True)

    def onCompletion(self, text):
        if self.lblAjax:
            self.lblAjax.setVisible(False)
        
    def onError(self, text, code):
        if self.lblAjax:
            self.lblAjax.setVisible(False)
        Window.alert("Error: " + text + "\nCodigo: " + code)

    def onTimeout(self, text):
        if self.lblAjax:
            self.lblAjax.setVisible(False)
        Window.alert("Timeout: " + text)


class HTMLLoader(AjaxLoader):
    def __init__(self, widget, lblAjax = None):
        self.widget = widget
        AjaxLoader.__init__(self, lblAjax)
        
    def onCompletion(self, text):
        AjaxLoader.onCompletion(self, text)
        self.widget.setText(text)


class JSONLoader(AjaxLoader):
    def __init__(self, func, lblAjax = None):
#        self.obj = obj
        self.func = func
        AjaxLoader.__init__(self, lblAjax)
        
    def onCompletion(self, text):
        AjaxLoader.onCompletion(self, text)
        self.func(text)



class MenuCmd:
    def __init__(self, object, handler):
        self._object  = object
        self._handler = handler

    def execute(self):
        handler = getattr(self._object, self._handler)
        handler()
                

        
class FormAbout(DialogBox):
    def __init__(self, title = "About...", autoHide = None):
        DialogBox.__init__(self, autoHide)
        self.setHTML(title)
        DOM.setStyleAttribute(self.getElement(), "backgroundColor", "#E7E7E7")
        DOM.setStyleAttribute(self.caption.getElement(), "backgroundColor", "#0D4B70")
        DOM.setStyleAttribute(self.caption.getElement(), "color", "#FFFFFF")
        panel = VerticalPanel()
        DOM.setStyleAttribute(panel.getElement(), "backgroundColor", "#E7E7E7")
        panel.setHorizontalAlignment("center")
        panel.add(Frame(url="about.html"))
        panel.add(HTML('<div style="background-color: #e7e7e7;">&nbsp;</div>'))
        btnok = Label("OK")
        btnok.addMouseListener(TooltipListener("Cerrar"))
        btnok.addClickListener(self)
        btnok.setStyleName("tooltip")
        DOM.setStyleAttribute(btnok.getElement(), "cursor", "pointer")
        DOM.setStyleAttribute(btnok.getElement(), "backgroundColor", "#E7E7E7")
        DOM.setStyleAttribute(btnok.getElement(), "width", "40px")
        DOM.setStyleAttribute(btnok.getElement(), "verticalAlign", "middle")
        panel.add(btnok)
        self.setWidget(panel)
        
    def onClick(self):
        self.hide()
        
    
class index:
    def onModuleLoad(self):
        self.frmAbout = FormAbout(autoHide = True)
        def fakeMouseMove(self, x, y):
            pass
        self.frmAbout.onMouseMove = fakeMouseMove
        self.frmAbout.setWidth(305)
        self.frmAbout.setHeight(250)
        left = (Window.getClientWidth() - 305) / 2
        top = (Window.getClientHeight() - 250) / 2
        self.frmAbout.setPopupPosition(left, top)

        self.lblAjax = HTML("""
                            <div style="position: absolute; right: 10px; top: 10px; color: #fff;
                            background-color: inherit;">
                            <img src="images/waiting2.gif"/>
                            </div>
                            """)
        self.lblAjax.setVisible(False);

        roundPanel = RoundPanel("""<div style="padding-top: 1em; padding-left: 1em; padding-bottom: 5em;
                                padding-right: 2em;"
                                id="central">
                                </div>""")
        DOM.setStyleAttribute(roundPanel.getElement(), "position", "absolute")
        DOM.setStyleAttribute(roundPanel.getElement(), "top", "10%")
        DOM.setStyleAttribute(roundPanel.getElement(), "left", "10%")
        DOM.setStyleAttribute(roundPanel.getElement(), "width", "80%")

        self.centralPanel = HTMLPanel("""<div id="menuDiv"></div><p></p><p></p><p></p>
                                      <div style="text-align: center;" id="clockDiv"></div>""")
        #self.centralPanel.setSpacing(16)
        roundPanel.add(self.centralPanel, "central")
        
        simple = SimplePanel()
        self.centralPanel.add(simple, "menuDiv")
        
        menuFiles = MenuBar(vertical=True)
        menuFiles.addItem("Open", MenuCmd(self, "onMenuOpen"))
        menuFiles.addItem("Exit", MenuCmd(self, "onMenuExit"))

        menuFuncs = MenuBar(vertical=True)
        menuFuncs.addItem("C.R.U.D. Example", MenuCmd(self, "onMenuFunction1"))
        menuFuncs.addItem("Function 2 - Show Tabbed Dialog", MenuCmd(self, "onMenuFunction2"))

        menuHelp = MenuBar(vertical=True)
        menuHelp.addItem("Help", MenuCmd(self, "onMenuHelp"))
        menuHelp.addItem("About", MenuCmd(self, "onMenuAbout"))

        menubar = MenuBar(vertical=False)
        menubar.addItem(MenuItem("Files", menuFiles))
        menubar.addItem(MenuItem("Functions", menuFuncs))
        menubar.addItem(MenuItem("<strong>Help</strong>", True, menuHelp))

        simple.add(menubar)
#        self.otroCrud = CrudPanel(self.lblAjax)
#        self.centralPanel.add(self.otroCrud)
#        self.otroCrud.requestList()
        
        img_url = 'images/clock.png'
        self.solar = SolarCanvas(img_url)
        self.solar.isActive = True
        self.centralPanel.add(self.solar, "clockDiv")
        
#        RootPanel().add(self.centralPanel)
        RootPanel().add(roundPanel)
        RootPanel().add(self.lblAjax)
        
        self.createDialog1()
        self.createDialog2()
#        self.solar.onTimer()
        
#        self._dialog1.requestList()
        
    def showDialog1(self):
        self._dialog1.show()

    def createDialog1(self):
        self._dialog1 = DialogBox(autoHide = True)
        self._dialog1.setHTML('ABM Afiliados')
        
        field0 = {'colName': 'id', 'colRepr': 'Id', 'isId': True, 'isVisible': False, 'colValue': '0'}
        field1 = {'colName': 'nombre', 'colRepr': 'Nombre', 'isId': False, 'isVisible': True, 'colValue': ''}
        field2 = {'colName': 'fechanac', 'colRepr': 'Nacimiento', 'isId': False, 'isVisible': True, 'colValue': ''}
        
#       Window.alert(field1["colName"])
#        Window.alert(field1["colName"] + " " + field2["colName"] + " " + field3["colName"])
        
        self.crudPanel = CrudPanel(tableName = "afiliados", fields = [field0, field1, field2],labelAjax = self.lblAjax)
        
        self._dialog1.setWidget(self.crudPanel)
        
        left = 150
        top = 120
        self._dialog1.setPopupPosition(left, top)

    def showCountryData(self):
        stri = ""
        stri += "Country: " + self.countrylist.getItemText(self.countrylist.getSelectedIndex()) + "\n"
        stri += "Code: " + self.countrylist.getValue(self.countrylist.getSelectedIndex())
        Window.alert(stri)
        
#        self.countrylist.removeChangeListener(borrame)
        
    def showDialog2(self):
        self._dialog2.show()
        
    def createDialog2(self):
        contents = VerticalPanel()
        contents.setSpacing(4)

        tabs = TabPanel()
        tabs.add(HTML("The quick brown fox jumps over the lazy dog."), "Tab 1")
        tabs.add(HTML("The early bird catches the worm."), "Tab 2")
        tabs.add(HTML("The smart money is on the black horse."), "Tab 3")
        
        self.countrylist = CountryListBox()
        self.countrylist.setSelectedIndex(11)
        self.countrylist.setVisibleItemCount(10)
#        self.countrylist.addChangeListener(borrame)
        self.countrylist.addChangeListener(getattr(self, "showCountryData"))
        tabs.add(self.countrylist, "Country List")
        
        ac = AutoCompleteTextBox()
        equipos = ["River Plate", "Boca Juniors", "Tiro Federal", "Newell's Old Boys", "Rosario Central",
                   "San Lorenzo", "Huracán", "Racing Club", "Independiente", "San Martín", "Estudiantes",
                   "Gimnasia y Esgrima", "Colón" "Velez Sarsfield"]
        ac.setCompletionItems(equipos)
        tabs.add(ac, "Equipos")
        
        tabs.selectTab(3)
        tabs.setWidth("300px")
        tabs.setHeight("100px")
        
        contents.add(tabs)
        
        contents.add(Button("Close", getattr(self, "onCloseDialog2")))
        contents.setStyleName("Contents")

        self._dialog2 = DialogBox()
        self._dialog2.setHTML('<b style="color: navy;">Tabbed Dialog Demo</b>')
        self._dialog2.setWidget(contents)

        left = (Window.getClientWidth() - 300) / 2
        top = (Window.getClientHeight() - 100) / 2 - 100
        self._dialog2.setPopupPosition(left, top)

    def onCloseDialog2(self):
        self._dialog2.hide()

    def onMenuOpen(self):
        Window.alert("Open")

    def onMenuExit(self):
        Window.alert("Exit")
        JS("window.close();")

    def onMenuHelp(self):
        Window.alert("Help")

    def onMenuAbout(self):
        self.frmAbout.show()
#        Window.alert("About...")

        
    def onMenuFunction1(self):
        self.crudPanel.requestList()
        self.showDialog1()

    def onMenuFunction2(self):
#        Window.alert("Function 2")
        self.showDialog2()
